﻿//#####################################################################
// PAGE LOAD

var urlToHandler = "/DesktopModules/DNNspot-ChatRoom/AjaxHandler.ashx";
var updateTranscriptDelay = 1500;
var pingDelay = 15000;

var portalId = 0;
var moduleId = 0;
var userId = -1;
var userIp = '';
var userHandle = '';
var maxAllowedUsers = 9999999;

var lastMessageId = -1;
var oldLastMessageId = lastMessageId;
var loggedIn = false;
var updatesStarted = false;

//#####################################################################
// TIMERS

function setupPingTimer() {
    if (userHandle != '')
        ping();

    var timer = setTimeout('setupPingTimer()', pingDelay);
}

//---------------------------------------------------------------------
// Timer callbacks

function ping() {
    var postData = {};
    postData.Action = "Ping";
    postData.PortalId = portalId;
    postData.ModuleId = moduleId;
    postData.UserHandle = userHandle;

    jQuery.post(
        urlToHandler,
        postData,
        null,
        "json"
    );
}

//#####################################################################
// SETUP FUNCTIONS

function loadSettings() {
    urlToHandler = String.format('{0}{1}AjaxHandler.ashx', jQuery('#hidApplicationPath').val(), jQuery('#hidModuleWebPath').val());
    portalId = jQuery('#hidPortalId').val();
    moduleId = jQuery('#hidModuleId').val();
    userId = jQuery('#hidUserId').val();
    userIp = jQuery('#hidUserIp').val();
}

//#####################################################################
// CALLBACKS

function handleMessagePost(data) {
    if (data != null && data.logout) {
        reset();
    }
}

function addUser(data) {
    if (data.success) {
        userHandle = jQuery('#txtUserHandle').val();
        lastMessageId = data.MessageId;
        loggedIn = true;

        jQuery('#txtLoginMessage').text('');

		if(!updatesStarted) {
			getRoomState();
			updatesStarted = true;
		}

        postMessage(String.format('/notice {0} joined the chat room', userHandle), '');        
        hideLogin();
    } else {
        jQuery('#txtLoginMessage').text(data.error);
        jQuery('#txtUserHandle').removeAttr('disabled').val('');
    }
}

function updateRoomState(data){
	if (loggedIn) {
		jQuery(data.Messages).each(function(i, obj){
			appendMessage(obj);
		});
	
		jQuery('#chatUsers').html('');
		jQuery(data.Users).each(function(i, obj){
			appendUser(obj);
		});
	}
	
	if(data.Messages.length > 0)
	    lastMessageId = data.Messages[(data.Messages.length - 1)].MessageId;
	
	if (oldLastMessageId != lastMessageId) {
		oldLastMessageId = lastMessageId;
		jQuery('#chatTranscripts').scrollTo('100%', 0);
	}
	
    getRoomState();
}

//#####################################################################
// MAIN FUNCTIONS

function hideLogin() {
    jQuery('#chatContainer').unblock();
    jQuery('#txtInput').focus();
}

function login() {
    jQuery('#txtUserHandle').attr('disabled', 'disabled');
    
    var postData = {};
    postData.Action = "AddUser";
    postData.PortalId = portalId;
    postData.ModuleId = moduleId;
    postData.UserId = userId;
    postData.UserHandle = jQuery('#txtUserHandle').val();
    postData.UserIp = userIp;
    postData.MaxAllowedUsers = maxAllowedUsers;

    jQuery.post(
        urlToHandler,
        postData,
        addUser,
        "json"
    );
}

function logout() {
    if (userHandle != '') {
        postMessage('/quit');
    }

    removeUser();
    reset();
}

function postMessage(message, handle) {
    var postData = {};
    postData.Action = "PostMessage";
    postData.PortalId = portalId;
    postData.ModuleId = moduleId;
    postData.UserId = userId;
    postData.UserIp = userIp;
    postData.UserHandle = userHandle;
    postData.Body = jQuery('#txtInput').val();

    if (typeof (handle) != 'undefined') {
        postData.UserId = -1;
        postData.UserHandle = handle;
    }

    if (typeof(message) != 'undefined')
        postData.Body = message;

    jQuery.post(
        urlToHandler,
        postData,
        handleMessagePost,
        "json"
    );

    jQuery('#txtInput').val('');
}

function removeUser() {
    var postData = {};
    postData.Action = "RemoveUser";
    postData.PortalId = portalId;
    postData.ModuleId = moduleId;
    postData.UserHandle = userHandle;

    jQuery.post(
        urlToHandler,
        postData,
        null,
        "json"
    );

    userHandle = '';
}

function reset() {
    userHandle = '';
	loggedIn = false;
    	
    loadSettings();    
    showLogin();
}

function showLogin() {
    jQuery('#chatContainer').block({
        message: jQuery('#chatHandleInput'),
        css: {
            padding: 10,
            cursor: 'pointer'
        }
    });
    
    jQuery('#txtUserHandle').removeAttr('disabled');
    jQuery('#txtUserHandle').focus();
}

function getRoomState() {
    var postData = {};
    postData.Action = "GetRoomState";
    postData.PortalId = portalId;
    postData.ModuleId = moduleId;
    postData.UserHandle = userHandle;
    postData.MessageId = lastMessageId;

    jQuery.post(
        urlToHandler,
        postData,
        updateRoomState,
        "json"
    );
}

//#####################################################################
// HELPER FUNCTIONS

function appendMessage(message){
	if (message.MessageId > lastMessageId) {
		var msg = String.format('<div class="message"><div class="handle">{0}</div><div class="body">{1}</div></div>', 
			message.UserHandle != '' ? message.UserHandle + ':' : '', 
			message.Body.replace(userHandle, '<span class="self">' + userHandle + '</span>', 'gi'));
			
		jQuery('#chatTranscripts').append(msg);
	}
}

function appendUser(user) {
     jQuery('#chatUsers').append(String.format(
        '<div class="user{0}"><span class="handle{1}">{2}</span></div>',
        user.IsAway ? ' away' : '',
        user.UserHandle == userHandle ? ' self' : '',
        user.UserHandle));
}

//#####################################################################
// PAGE LOAD

jQuery(function() {
    reset();

    setupPingTimer();

    window.onbeforeunload = function() {
        logout();
    };

    window.onunload = function() {
        logout();
    };

    jQuery(window).unload(function() {
        logout();
    });

    jQuery('#txtInput').keypress(function(e) {
        if (e.keyCode == 13) {
            e.stopPropagation();
            e.preventDefault();

            postMessage();
        }
    });

    jQuery('#txtUserHandle').keypress(function(e) {
        if (e.keyCode == 13) {
            e.stopPropagation();
            e.preventDefault();

            login();
        }
    });
});